package cn.highedu.http;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ServerBootApplication {
    private ServerSocket serverSocket;
    private ThreadPoolExecutor executor;

    private void initThreadPool(){
        int corePoolSize = 20;
        int maxPoolSize = 50;
        int keepAliveTime = 5000;
        int queueSize = 200;
        //自定义创建线程池
        executor = new ThreadPoolExecutor(
                corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.MICROSECONDS,
                new LinkedBlockingQueue<>(queueSize),
                new ThreadFactoryBuilder().setNameFormat("Worker-%d").build(),  //自定义线程名
                new ThreadPoolExecutor.AbortPolicy()
        );
    }

    private void start(){
        try {
            initThreadPool();
            serverSocket = new ServerSocket(8089);
            while (true){
                System.out.println("等待连接");
                Socket socket = serverSocket.accept();
                System.out.println("已经连接");
                ClientHandler clientHandler = new ClientHandler(socket);
                //Thread thread = new Thread(clientHandler);
                //thread.start();
                executor.execute(clientHandler);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ServerBootApplication application = new ServerBootApplication();
        application.start();
    }
}
